<?php
/**
 * Created by PhpStorm.
 * User: xiaolang
 * Date: 2017/8/24
 * Time: 11:05
 */

namespace App\Http\Middleware;

use App\ConstDir\ErrorConst;
use Illuminate\Http\JsonResponse;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

/*
 * 后台认证
 */
class Authenticate extends BaseMiddleware
{
    /**
     * 后台认证
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        if (! $token = $this->auth->setRequest($request)->getToken()) {
            return new JsonResponse([
                'code' => ErrorConst::NOT_LOGIN,
                'message' => ErrorConst::NOT_LOGIN_MSG,
                'data' => null
            ]);
        }
        
        //认证范围判断
        $payload = $this->auth->decode($token);
        if($payload->offsetExists('scope') && $payload['scope'] == 'backend'){
            
        }else{
            throw new TokenInvalidException();
        }
        
        $user = $this->auth->authenticate($token);
        if (! $user) {
            return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
        }
        $this->events->fire('tymon.jwt.valid', $user);

        return $next($request);
    }
}